# frozen_string_literal: true

require 'faye/websocket'
require 'eventmachine'
require 'singleton'
require 'json'

class WebSocketHelper
  include Singleton

  @socket = nil
  @messages = []

  def self.connect
    Thread.new { connect_websocket }
  end

  def self.messages
    @messages
  end

  def self.connect_websocket
    return unless @socket.nil?

    EM.run do
      @socket = Faye::WebSocket::Client.new("ws://movienight:#{MOVIENIGHT_WS_PORT}/ws")

      @socket.on :open do |_event|
        p [:open]
        @socket.send({ Type: 6, Message: { Name: 'socket', Color: '#ffffff' }.to_json }.to_json)
      end

      @socket.on :message do |event|
        @messages << JSON.parse(event.data)
      end

      @socket.on :close do |_event|
        @socket = nil
      end
    end
  end

  def self.clear_cache
    @messages = []
  end

  def send(message)
    @socket.send({ Type: 0, Message: message }.to_json)
  end
end
